<script setup>
import { ref, computed, watch } from 'vue';
import { Edit, Delete, Plus } from '@element-plus/icons-vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import * as XLSX from 'xlsx';

const route = useRoute(); // 获取当前路由对象
const examSelected_Id = ref(route.query.e_id); // 从路由的 query 中提取 e_id 并保存为响应式变量
const examSelected_Name = ref(route.query.e_name); // 从路由的 query 中提取 e_name 并保存为响应式变量

const isAnalysisCompleted = ref(false);  // excel文件是否解析完成
const batchStudentsData = ref([]); // 使用 ref 声明响应式数组

// 路由对象
const router = useRouter();

function goBack() {
    router.push({
        path: "/teacher/home",
    });
}

// 学生列表数据
const students = ref([
    {
        "s_id": "2024001",
        "s_name": "张三",
        "s_class": "一班",
        "s_fpath": "https://exam-qique.oss-cn-beijing.aliyuncs.com/001.png",
        "s_fname": "作业1.docx",
        "s_score": 85,
        "s_comment": "优秀",
    },
    {
        "s_id": "2024002",
        "s_name": "李四",
        "s_class": "二班",
        "s_fpath": "",
        "s_fname": "作业2.docx",
        "s_score": 90,
        "s_comment": "很好",
    },
    {
        "s_id": "2024003",
        "s_name": "张三",
        "s_class": "一班",
        "s_fpath": "path/to/file1",
        "s_fname": "作业1.docx",
        "s_score": 85,
        "s_comment": "优秀",
    },
    {
        "s_id": "2024004",
        "s_name": "李四",
        "s_class": "二班",
        "s_fpath": "path/to/file2",
        "s_fname": "作业2.docx",
        "s_score": 90,
        "s_comment": "很好",
    },
    {
        "s_id": "2024005",
        "s_name": "张三",
        "s_class": "一班",
        "s_fpath": "path/to/file1",
        "s_fname": "作业1.docx",
        "s_score": 85,
        "s_comment": "优秀",
    },
    {
        "s_id": "2024006",
        "s_name": "李四",
        "s_class": "二班",
        "s_fpath": "path/to/file2",
        "s_fname": "作业2.docx",
        "s_score": 90,
        "s_comment": "很好",
    },
    {
        "s_id": "2024007",
        "s_name": "张三",
        "s_class": "一班",
        "s_fpath": "path/to/file1",
        "s_fname": "作业1.docx",
        "s_score": 85,
        "s_comment": "优秀",
    },
    {
        "s_id": "2024008",
        "s_name": "李四",
        "s_class": "二班",
        "s_fpath": "path/to/file2",
        "s_fname": "作业2.docx",
        "s_score": 90,
        "s_comment": "很好",
    },
    {
        "s_id": "2024009",
        "s_name": "张三",
        "s_class": "一班",
        "s_fpath": "path/to/file1",
        "s_fname": "作业1.docx",
        "s_score": 85,
        "s_comment": "优秀",
    },
    {
        "s_id": "2024010",
        "s_name": "李四",
        "s_class": "二班",
        "s_fpath": "path/to/file2",
        "s_fname": "作业2.docx",
        "s_score": 90,
        "s_comment": "很好",
    },
]);

// 分页后的学生数据
const paginatedStudents = computed(() => {
    const start = (pageNum.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    return students.value.slice(start, end);
});

// 考生数据模型
const studentData = ref({
    // 发送添加考生请求时的必填信息
    s_id: null,  // 学生学号
    s_name: '',  // 学生姓名
    s_class: '', // 学生班级
    e_id: null,  // 该学生所参加的考试id号

    // 以下非添加考试时的必填信息，由后端修改或后续的用户修改
    s_score: null, // 该学生的得分
    s_comment: '', // 对该学生的评语
    s_fpath: '',   // 该学生上传的考卷文件的下载路径
    s_fname: '',   // 该学生上传的考卷文件的名称
})

import { studentListByExamIdService, studentSearchService, studentAddService, studentUpdateService, studentDeleteService, studentBatchAddService } from '@/api/student.js'

// 声明一个异步的函数,获取某场考试的学生列表
const getStudentList = async (examSelected_Id) => {
    try {
        let result = await studentListByExamIdService(examSelected_Id);
        students.value = result.data;
    } catch (error) {
        ElMessage.error('获取列表失败');
    }
}

// 调用查询
getStudentList(examSelected_Id.value);

// 通过个人信息搜索学生
const searchStudentByInformation = async (studentData) => {
    try {
        let result = await studentSearchService(studentData);
        students.value = result.data;

        // 如果返回的是空数组
        if (students.value = []) {
            ElMessage.info('未检索到符合要求的学生信息');
        }

    } catch (error) {
        ElMessage.error('获取列表失败');
    }
    // 清空表单
    resetForm();
};

// 重置学生列表
const resetList = () => {
    resetForm();
    getStudentList(examSelected_Id.value);
}

// 抽屉状态
const visibleDrawer = ref(false);

// 触发抽屉时是否为编辑学生信息。
const isEditing = ref(false);

// 点击新增考试打开抽屉
const openDrawer = () => {
    visibleDrawer.value = true;
    isEditing.value = false;
    resetForm();
    batchStudentsData.value = [];
};

// 关闭抽屉
const closeDrawer = () => {
    visibleDrawer.value = false;
    resetForm();
};

// 清空学生数据模型的表单
const resetForm = () => {
    studentData.value = {
        s_id: '',
        s_name: '',
        s_class: '',
        s_score: '',
        s_comment: '',
        s_fpath: '',   // 该学生上传的考卷文件的下载路径
        s_fname: ''   // 该学生上传的考卷文件的名称
    };
};


// 按下抽屉中“保存”键后，根据情景不同调用相关函数
const handleSubmit = () => {
    isEditing.value ? updateStudent() : addStudent();
};

// 添加学生
const addStudent = async () => {
    if (!studentData.value.s_id || !studentData.value.s_name || !studentData.value.s_class) {
        ElMessage.warning('请完整填写学生信息');
        return;
    }
    try {
        let result = await studentAddService(studentData.value);
        // 根据服务端返回的msg信息是否为空，判断是否添加成功
        ElMessage.success(result.msg ? result.msg : '学生已添加');

    } catch (error) {
        ElMessage.error('添加学生请求超时');
    }
    // 刷新学生列表
    getStudentList(examSelected_Id.value);
    closeDrawer();
};



// 读取 Excel 文件并将数据导入batchStudentsData
const handleFile = (file) => {
    const reader = new FileReader();

    reader.onload = (e) => {
        const data = new Uint8Array(e.target.result);
        const workbook = XLSX.read(data, { type: 'array' });
        const sheetName = workbook.SheetNames[0]; // 读取第一个表
        const sheet = workbook.Sheets[sheetName];
        const rawData = XLSX.utils.sheet_to_json(sheet, { header: 1 }); // 转换为二维数组

        // 处理数据并生成学生数组
        batchStudentsData.value = rawData.slice(1).map((row) => ({
            s_id: row[0] || null,
            s_name: row[1] || '',
            s_class: row[2] || '',
            e_id: examSelected_Id.value,
            s_score: null,
            s_comment: '',
            s_fpath: '',
            s_fname: '',
        }));
        console.log('解析后的学生数据:', batchStudentsData.value);
        // 解析完毕
        isAnalysisCompleted.value = true;
    };
    reader.readAsArrayBuffer(file.raw);
};

// 批量导入考生
const batchAddStudents = async () => {
    try {
        let result = await studentBatchAddService(batchStudentsData.value);
        // 根据服务端返回的msg信息是否为空，判断是否添加成功
        ElMessage.success(result.msg ? result.msg : '批量添加成功');

    } catch (error) {
        ElMessage.error('批量添加请求超时');
    }

    // 刷新学生列表
    getStudentList(examSelected_Id.value);
    // 置空
    batchStudentsData.value = [];
    isAnalysisCompleted.value = false;
    closeDrawer();
}

// 删除学生
const deleteStudent = (id) => {
    ElMessageBox.confirm('确定要删除此学生吗？', '提示', {
        type: 'warning',
    }).then(async () => {
        try {
            let result = await studentDeleteService(id);
            // 根据服务端返回的msg信息是否为空，判断是否删除成功
            ElMessage.success(result.msg ? result.msg : '删除成功');
            // 刷新学生列表
            getStudentList(examSelected_Id.value);
        } catch (error) {
            ElMessage.error('删除请求超时');
        }
    });
};

// 修改学生信息（主要是分数和评语）
const editStudent = (row) => {
    isEditing.value = true;
    visibleDrawer.value = true;
    studentData.value = { ...row }; // 填充数据
};

// 更新学生信息
const updateStudent = async () => {
    try {
        // 调用学生信息修改接口
        let result = await studentUpdateService(studentData.value);
        // 根据服务端返回的msg信息是否为空，判断是否更新成功
        ElMessage.success(result.msg ? result.msg : '学生信息已更新');
        // 刷新学生列表
        getStudentList(examSelected_Id.value);
    } catch (error) {
        ElMessage.error('学生信息编辑请求超时');
    }
    closeDrawer();
};


// 页面具体数据信息
const pageNum = ref(1); // 当前页
const pageSize = ref(3); // 每页条数
const total = ref(students.value.length); // 总条数

// 页大小改变
const onSizeChange = (size) => {
    pageSize.value = size;
    pageNum.value = 1; // 重置到第一页
};

// 页码改变
const onPageChange = (page) => {
    pageNum.value = page;
};

// 监听 students 数组变化，实时更新 total 值
watch(
    () => students.value,
    (newVal) => {
        total.value = newVal.length;
    },
    { deep: true }
);

</script>


<template>
    <el-card>
        <template #header>
            <div class="header">
                <el-button type="primary" @click="goBack()">返回</el-button>

                <h1>{{ examSelected_Name + '(id:' + examSelected_Id + ')' }}</h1>

                <el-button type="primary" @click="openDrawer()">添加学生</el-button>
            </div>
        </template>

        <!-- 搜索表单 -->
        <el-form inline :model="studentData">
            <el-form-item label="学号">
                <el-input v-model="studentData.s_id" placeholder="请输入学号" />
            </el-form-item>
            <el-form-item label="姓名">
                <el-input v-model="studentData.s_name" placeholder="请输入姓名" />
            </el-form-item>
            <el-form-item label="班级">
                <el-input v-model="studentData.s_class" placeholder="请输入班级" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="searchStudentByInformation(studentData)">搜索</el-button>
                <el-button @click="resetList()">重置</el-button>
            </el-form-item>
        </el-form>
        <br>
        <!-- <h1>{{ studentData }}</h1> -->
        <h1>{{ batchStudentsData }}</h1>

        <!-- 学生成绩表格 -->
        <el-table :data="paginatedStudents" style="width: 100%">
            <el-table-column label="学号" prop="s_id"></el-table-column>
            <el-table-column label="姓名（班级）">
                <template #default="{ row }">
                    {{ row.s_name }}（{{ row.s_class }}）
                </template>
            </el-table-column>
            <el-table-column label="答卷">
                <template #default="{ row }">
                    <template v-if="row.s_fpath">
                        <a :href="row.s_fpath" :download="row.s_fname">{{ row.s_fname }}</a>
                    </template>
                    <span v-else>未上传</span>
                </template>
            </el-table-column>
            <el-table-column label="分数">
                <template #default="{ row }">
                    <el-input-number v-if="row.editable" v-model="row.s_score" :min="0" :max="100" />
                    <span v-else>{{ row.s_score }}</span>
                </template>
            </el-table-column>
            <el-table-column label="评语">
                <template #default="{ row }">
                    <el-input v-if="row.editable" v-model="row.s_comment" placeholder="请输入评语" />
                    <span v-else>{{ row.s_comment }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #default="{ row }">
                    <el-button :icon="Edit" circle plain type="primary" @click="editStudent(row)"></el-button>
                    <el-button :icon="Delete" circle plain type="danger" @click="deleteStudent(row.id)"></el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页条   5555-->
        <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5, 10, 15]"
            layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
            @current-change="onPageChange" style="margin-top: 20px; justify-content: flex-end" />


        <!-- 添加/编辑学生的抽屉 -->
        <el-drawer v-model="visibleDrawer" :title="isEditing ? '编辑学生信息' : '添加学生信息'" size="40%">
            <el-form :model="studentData" label-width="80px">
                <el-form-item label="学号">
                    <el-input v-model="studentData.s_id" placeholder="请输入学号" :disabled="isEditing" />
                </el-form-item>
                <el-form-item label="姓名">
                    <el-input v-model="studentData.s_name" placeholder="请输入姓名" />
                </el-form-item>
                <el-form-item label="班级">
                    <el-input v-model="studentData.s_class" placeholder="请输入班级" />
                </el-form-item>
                <el-form-item v-if="isEditing">
                    <el-form-item label="成绩">
                        <el-input v-model="studentData.s_score" placeholder="请输入成绩" />
                    </el-form-item>
                    <el-form-item label="评语">
                        <el-input v-model="studentData.s_comment" placeholder="请输入评语" />
                    </el-form-item>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSubmit">保存</el-button>
                    <el-button @click="closeDrawer">取消</el-button>
                </el-form-item>
                <!-- 在此处添加一个功能，从excel表格文件（前三列分别对应,学号，姓名，班级）中批量添加考生（且仅在添加考生时显示启用） -->
                <hr>
                <el-form-item v-if="!isEditing">
                    <el-upload accept=".xlsx, .xls" action="" :before-upload="() => false" :on-change="handleFile">
                        <el-button type="primary">上传Excel文件</el-button>
                    </el-upload>
                </el-form-item>
                <el-form-item v-if="!isEditing">
                    <el-button type="primary" :disabled="!isAnalysisCompleted" @click="batchAddStudents()">
                        批量导入
                    </el-button>
                </el-form-item>

            </el-form>
        </el-drawer>

    </el-card>
</template>


<style scoped>
.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.upload-demo {
    margin: 10px 0;
}
</style>
